<!-- 新增修改地址 -->
<template>
    <div>
        <app-head :nickname-value="userInfo.nickname" :avatarValue="userInfo.avatar"></app-head>
        <app-body>
            <!-- 编辑收获地址 -->
                <div class="address-container-add">
                    <div class="address-container-add-title"><b> 新增收货地址：</b></div>
                   
                    <!-- 输入收件人姓名 -->
                    <div class="address-container-add-item">
                        <el-input placeholder="请输入收货人姓名" v-model="addressInfo.consigneeName" maxlength="10" show-word-limit>
                            <div slot="prepend">收货人姓名</div>
                        </el-input>
                    </div>
                   
                    <!-- 输入收件人手机号 -->
                    <div class="address-container-add-item">
                        <!-- 键盘事件处理器  匹配所有非数字和非点的字符 替换 空-->
                        <el-input placeholder="请输入收货人手机号" v-model="addressInfo.consigneePhone"
                            onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" maxlength="11" show-word-limit>
                            <div slot="prepend">手机号</div>
                        </el-input>
                    </div>

                    <!-- 选择省市区  级联选择器-->
                    <div class="address-container-add-item">
                        <span class="demonstration">省/市/区</span>
                                    <!--单向匹配-->        <!--双向匹配-->         <!--事件监听器--> 
                        <el-cascader :options="options" v-model="selectedOptions" @change="handleAddressChange"
                            :separator="' '">
                        </el-cascader>
                    </div>
                    
                    <!-- 输入详细地址 -->
                    <div class="address-container-add-item">
                        <el-input placeholder="请输入详细地址（如道路、门牌号、小区、楼栋号等信息）" v-model="addressInfo.detailAddress"
                            maxlength="50" show-word-limit>
                            <div slot="prepend">详细地址</div>
                        </el-input>
                    </div>

                    <el-button type="success" style="margin-left: 20px;" @click="saveAddress"> 保存</el-button>
                </div>
                
                <div class="address-container-list">
                    <div style="color: black;padding-left: 10px;font-size: 26px;"><b>已存在的收货地址：</b></div>
                    <br>
                    <el-table stripe :data="addressData" style="width: 100%">
                        <!-- 这一列的名字 -->
                        <el-table-column prop="consigneeName" label="收货人姓名" width="100">
                        </el-table-column>
                        
                        <el-table-column prop="consigneePhone" label="手机号" width="120">
                        </el-table-column>
                        
                        <el-table-column prop="detailAddressText" label="地址" width="270">
                        </el-table-column>

                        <!-- 改成默认地址 -->
                        <el-table-column label="是否默认地址" width="110">
                            <template slot-scope="scope">

                                <!-- 设为默认 button   如果当前行不是默认，则显示一个按钮-->
                                <el-button v-if="!scope.row.defaultFlag" size="mini"
                                    @click="handleSetDefault(scope.$index, scope.row)">设为默认
                                </el-button>
                               
                                     <!-- 当前行是默认地址 打印出来 -->                     <!-- 插值表达式 -->
                                     <div v-else class="default-address">{{ scope.row.defaultAddress }}
                                </div>
                            </template>
                        </el-table-column>

                        <!-- 编辑和删除 -->
                        <el-table-column label="操作" width="250" fixed="right">
                            <template slot-scope="scope">
                                <el-button type="primary"  @click="handleEdit(scope.$index, scope.row)"> 编辑
                                </el-button>
                                
                                <el-button type="danger" @click="handleDelete(scope.$index, scope.row)"> 删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
        </app-body>
        <app-foot></app-foot>
    </div>
</template>

<script>
import AppHead from '../common/AppMeHeader.vue';
import AppBody from '../common/AppPageBody.vue'
import AppFoot from '../common/AppFoot.vue'
import options from '../common/country-data.js'

export default {
    name: "address",//组件的名字，不影响路由
    components: {//使用这些组件
        AppHead,
        AppBody,
        AppFoot
    },
    data() {//组件的初始数据
        return {
            addressInfo: {//地址信息
                consigneeName: '',
                consigneePhone: '',
                provinceName: '',
                cityName: '',
                regionName: '',
                detailAddress: '',
                defaultFlag: false //当前行不是默认地址
            },

            selectedOptions: [],//存放选择的地址 默认值为空
            options: options,   //存放城市数据的数组
            userInfo: {//用户信息
                accountNumber: "",
                avatar: "",
                nickname: "",
                signInTime: "",
            },
            addressData: []
        };
    },
    created() {//生命周期钩子，页面加载时调用  显示已经存在的地址
        if (!this.$globalData.userInfo.nickname) {//不存在则请求用户信息
            this.$api.getUserInfo().then(res => {//请求用户信息
                if (res.status_code === 1) {
                    res.data.signInTime = res.data.signInTime.substring(0, 10);
                    console.log(res.data);
                    this.$globalData.userInfo = res.data;
                    this.userInfo = this.$globalData.userInfo;
                }
            })
        } else {//存在用户信息则直接赋值
            this.userInfo = this.$globalData.userInfo;
            console.log(this.userInfo);
        }
        this.getAddressData();//获取用户地址
    },
    methods: {
        getAddressData() {//获取用户地址
            this.$api.getAddress().then(res => {//问后端要地址信息
                if (res.status_code === 1) {
                    let data = res.data;//从响应中获取数据，并将其存储在data变量中
                    for (let i = 0; i < data.length; i++) {
                        data[i].detailAddressText = data[i].provinceName + data[i].cityName + data[i].regionName + data[i].detailAddress;//把属性连起来
                        data[i].defaultAddress = data[i].defaultFlag ? '默认地址' : '设为默认';
                    }
                    console.log(data);
                    this.addressData = data;//代码处理后的data赋值
                }
            })
        },
        handleAddressChange(value) {//选择地址
            console.log(value);
            this.addressInfo.provinceName = value[0];
            this.addressInfo.cityName = value[1];
            this.addressInfo.regionName = value[2];
        },
        handleEdit(index, row) {//编辑地址
            console.log(index, row);
            this.addressInfo = JSON.parse(JSON.stringify(row));
            this.selectedOptions = ['', '', ''];
            this.selectedOptions[0] = row.provinceName;
            this.selectedOptions[1] = row.cityName;
            this.selectedOptions[2] = row.regionName;
        },
        handleDelete(index, row) {//删除地址
            console.log(index, row);
            this.$confirm('是否确定删除该地址?', '提示', {//弹出提示框
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {//确认删除
                this.$api.deleteAddress(row).then(res => {//调用api里面的接口改后端数据
                    if (res.status_code === 1) {//返回的respond  删除成功
                        this.$message({
                            message: '删除成功！',
                            type: 'success'
                        });
                        this.addressData.splice(index, 1);//删除第一个元素
                        if (row.defaultFlag && this.addressData.length > 0) {//检查是否还有默认地址
                            this.addressData[0].defaultFlag = true;//第一个元素设置为默认地址
                            this.addressData[0].defaultAddress = '默认地址';
                            this.update({//代码更新后端的数据，将 addressData 数组中的第一个元素设置为默认地址。
                                id: this.addressData[0].id,
                                defaultFlag: true
                            });
                        }
                    } else {//没有删除成功
                        this.$message.error('系统异常，删除失败！')
                    }
                }).catch(() => {//没能调动通往后端的接口
                    this.$message.error('网络异常！')
                });
            }).catch(() => {
            });
        },
        handleSetDefault(index, row) {//设置默认地址
            console.log(index, row);//把点击对应的行设成默认地址
            row.defaultFlag = true;
            this.update(row);
        },
        update(data) {//更新地址
            this.$api.updateAddress(data).then(res => {//调用后端修改接口
                if (res.status_code === 1) {//返回值1，后端修改成功
                    this.getAddressData();
                    this.$message({//弹出信息
                        message: '修改成功！',
                        type: 'success'
                    });
                } else {
                    this.$message.error('系统异常，修改失败！')
                }
            }).catch(() => {
                this.$message.error('网络异常！')
            })
        },
        saveAddress() {//  保存地址
            if (this.addressInfo.id) {//检查有id吗，有，表示这是一个已存在的地址，需要更新
                console.log('update:', this.addressInfo);
                this.update(this.addressInfo);//调用上面的update方法更新地址信息
                this.addressInfo = {//将 addressInfo 对象的值重置为一个新的对象
                    consigneeName: '',
                    consigneePhone: '',
                    provinceName: '',
                    cityName: '',
                    regionName: '',
                    detailAddress: '',
                    defaultFlag: false//不是默认地址
                };
                this.selectedOptions = [];//将手动选择的地址数组的值重置为空数组。
            } else {
                if (this.addressData.length >= 5) {
                    this.$message.error('已达到最大地址数量！')
                } else {
                    console.log(this.addressInfo);
                    this.$api.addAddress(this.addressInfo).then(res => {//调用方法向后台发送请求post
                        if (res.status_code === 1) {
                            this.getAddressData();
                            this.$message({
                                message: '新增成功！',
                                type: 'success'
                            });
                            this.selectedOptions = [];//将手动选择的地址数组的值重置为空数组
                            this.addressInfo = {
                                consigneeName: '',
                                consigneePhone: '',
                                provinceName: '',
                                cityName: '',
                                regionName: '',
                                detailAddress: '',
                                defaultFlag: false//不是默认地址
                            };
                        } else {//返回码不是1，新增失败
                            this.$message.error('系统异常，新增失败！')
                        }
                    }).catch(e => {
                        this.$message.error('网络异常！')
                    })
                }
            }
        }
    }
}
</script>

<style scoped>
.edit-tip {
    font-size: 14px;
    margin: 10px 5px;
}

.address-container {
    padding: 20px;
    background: #f9f9f9;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.address-container-back {
    margin-bottom: 20px;
    font-size: 18px;
    color: #333;
    cursor: pointer;
}

.address-container-add-title {
    color: #333;
    padding: 20px 0;
    font-size: 24px;
    font-weight: bold;
    border-bottom: 2px solid #eee;
}

.address-container-add-item {
    margin-bottom: 20px;
}
.default-address {
    padding-left: 10px;
    color: #409EFF;
}
.el-input,
.el-cascader,
.el-checkbox {
    width: 100%;
    margin-bottom: 20px;
}

.el-input__inner,
.el-cascader__input {
    border-radius: 5px;
    border: 1px solid #ccc;
    padding: 10px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.el-input__inner:focus,
.el-cascader__input.is-focus {
    border-color: #409EFF;
}

.el-button {
    border-radius: 5px;
    padding: 10px 20px;
}

.address-container-add {
    background: #fff;
    padding: 20px 40px;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.address-container-list {
    padding: 30px 40px;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin-top: 20px;
}

.el-table {
    border-radius: 10px;
    overflow: hidden;
}

.el-table th, 
.el-table td {
    padding: 12px 10px;
}

.el-button[type="primary"] {
    background-color: #409EFF;
    border-color: #409EFF;
}

.el-button[type="danger"] {
    background-color: #f56c6c;
    border-color: #f56c6c;
}
</style>